package com.yincheng.oes.business.util.echartconvert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yincheng.oes.business.util.Consists;
import com.yincheng.oes.business.util.HttpUtil;
import freemarker.template.TemplateException;
import org.apache.http.client.ClientProtocolException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EchartsUtil {

    private static final String SUCCESS_CODE = "1";

    public static String generateEchartsBase64(List<Double> scores, List<Double> countryScores,
                                               List<Double> reviseScores) throws ClientProtocolException, IOException, TemplateException {
        String option = getOption(scores, countryScores, reviseScores);

        String base64 = getBase64(option);

        return base64;
    }

    public static String getBase64(String option) throws ClientProtocolException, IOException {
        String base64 = "";
        if (option == null) {
            return base64;
        }
        option = option.replaceAll("\\s+", "").replaceAll("\"", "'");

        // 将option字符串作为参数发送给echartsConvert服务器
        Map<String, String> params = new HashMap<>();
        params.put("opt", option);
        String response = HttpUtil.post(Consists.ECHARTS_SERVER_URL, params, "utf-8");

        // 解析echartsConvert响应
        JSONObject responseJson = JSON.parseObject(response);
        String code = responseJson.getString("code");

        // 如果echartsConvert正常返回
        if (SUCCESS_CODE.equals(code)) {
            base64 = responseJson.getString("data");
        }
        // 未正常返回
        else {
            String string = responseJson.getString("msg");
            throw new RuntimeException(string);
        }
        return base64;
    }

    private static String getOption(List<Double> scores, List<Double> countryScores, List<Double> reviseScores)
            throws IOException, TemplateException {
        String option = null;
        HashMap<String, Object> datas = new HashMap<>();
        datas.put("values", JSON.toJSONString(scores));
        datas.put("countryValues", JSON.toJSONString(countryScores));
        datas.put("reviseValues", JSON.toJSONString(reviseScores));
        option = FreemarkerUtil.generateString("echarts-测评分析模板.ftl", datas);
        return option;
    }
}
